package com.atguigu.IO;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *  实现TCP的网络编程
 *  例子1:客户端发送信息给服务端，服务端将数据显示在控制台上
 */
public class TCPTest1 {
    //客户端
    @Test
    public void client() throws IOException {
        Socket socket= null;
        OutputStream outputStream = null;
        try {
            InetAddress inet=InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet,8899);
            outputStream = socket.getOutputStream();
            outputStream.write("你干嘛哎哟喂".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(outputStream!=null){
                outputStream.close();
            }
            if(socket!=null){
                socket.close();
            }
        }
    }

    //服务端
    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = null;
        Socket socket= null;
        InputStream inputStream = null;
        try {
            serverSocket = new ServerSocket(8899);
            socket = serverSocket.accept();
            inputStream = socket.getInputStream();
            //不建议这样写，可能会有乱码
            byte[] buffer=new byte[200];
            int len;
            while((len=inputStream.read(buffer))!=-1){
                String str=new String(buffer,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(inputStream!=null){
                inputStream.close();
            }
            if(socket!=null){
                socket.close();
            }
            if(serverSocket!=null){
                serverSocket.close();
            }
        }
    }
}
